package com.xjoyt.pay.master.dao.predicate;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.xjoyt.pay.annotations.PredicateCommand;
import com.xjoyt.pay.master.params.ChannelPageParam;
import com.xjoyt.pay.master.po.Channel;

public class ChannelCommands {

	@PredicateCommand
	public List<Predicate> queryCommand(ChannelPageParam param, Root<Channel> root, CriteriaQuery<?> query,
			CriteriaBuilder cb) {
		if (StringUtils.isBlank(param.query))
			return null;

		List<Predicate> list = new ArrayList<>();
		for (String string : param.query.split(" ")) {
			if (StringUtils.isBlank(string))
				continue;
			String like = "%" + string + "%";
			list.add(cb.or(cb.like(root.get("no"), like), cb.like(root.get("name"), like)));
		}

		return list;
	}

	@PredicateCommand
	public List<Predicate> enabledCommand(ChannelPageParam param, Root<Channel> root, CriteriaQuery<?> query,
			CriteriaBuilder cb) {
		if (param.enabled == null)
			return null;

		List<Predicate> list = new ArrayList<>();

		if (param.enabled)
			list.add(cb.equal(root.get("enabled"), param.enabled));
		else
			list.add(cb.or(cb.equal(root.get("enabled"), false), cb.isNull(root.get("enabled"))));

		return list;
	}

	@PredicateCommand
	public List<Predicate> healthEnabledCommand(ChannelPageParam param, Root<Channel> root, CriteriaQuery<?> query,
			CriteriaBuilder cb) {
		if (param.healthEnabled == null)
			return null;

		List<Predicate> list = new ArrayList<>();

		if (param.healthEnabled)
			list.add(cb.equal(root.get("healthEnabled"), param.healthEnabled));
		else
			list.add(cb.or(cb.equal(root.get("healthEnabled"), false), cb.isNull(root.get("healthEnabled"))));

		return list;
	}

	@PredicateCommand
	public List<Predicate> parentIdCommand(ChannelPageParam param, Root<Channel> root, CriteriaQuery<?> query,
			CriteriaBuilder cb) {
		if (StringUtils.isBlank(param.parentId))
			return null;
		List<Predicate> list = new ArrayList<>();
		list.add(cb.or(cb.equal(root.get("company").get("id"), param.parentId),
				cb.like(root.get("company").get("path"), "%" + param.parentId + "%")));
		return list;
	}

	@PredicateCommand
	public List<Predicate> parentListCommand(ChannelPageParam param, Root<Channel> root, CriteriaQuery<?> query,
			CriteriaBuilder cb) {
		if (CollectionUtils.isEmpty(param.parentList))
			return null;
		List<Predicate> list = new ArrayList<>();
		list.add(root.get("company").get("id").in(param.parentList));
		return list;
	}

}
